package com.hcms.admin.filter.impl;

import com.hcms.admin.filter.AuthenticationTokenFilter;
import com.hcms.common.config.CmsJwtProperties;
import com.hcms.common.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 */
@Component
public class JwtAuthenticationTokenFilter implements AuthenticationTokenFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private CmsJwtProperties jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("Run doFilter()");
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String authHeader = httpServletRequest.getHeader(jwtConfig.getTokenHeader());
            logger.info("Filter the token requested by the user, header={}", authHeader);
            if (authHeader != null && authHeader.startsWith(jwtConfig.getTokenPrefix())) {
                String authToken = authHeader.substring(jwtConfig.getTokenPrefix().length());
                String username = jwtTokenUtil.getUserNameFromToken(authToken);
                logger.info("Checking username:{}", username);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    logger.info("Obtain user data");
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    if (jwtTokenUtil.verify(authToken) && username.equals(userDetails.getUsername())) {
                        logger.info("User token authentication succeeded");
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } else {
                        logger.error("User token authentication failed");
                    }
                }
            }
            logger.info("The token filtering is complete");
        } else {
            logger.error("'request' is not an HttpServletRequest instance");
        }
        chain.doFilter(request, response);
    }
}
